@page
@using Microsoft.AspNetCore.Antiforgery
@using Microsoft.AspNetCore.Authorization
@using Microsoft.Extensions.Options
@using Passwordless.AdminConsole.Services.PasswordlessManagement
@inject IOptionsSnapshot<PasswordlessOptions> PasswordlessOptions
@inject IOptionsSnapshot<PasswordlessManagementOptions> ManagementOptions
@inject IAntiforgery Antiforgery
@attribute [AllowAnonymous]
@model LoginModel

@{
    ViewData["Title"] = "Signin";
    var requestToken = Antiforgery.GetAndStoreTokens(Model.HttpContext).RequestToken;
}

@{
    ViewData["Title"] = "Home page";
    ViewData["HideTitle"] = true;
}

<div id="xapp" class="flex gap-6 flex-col mt-16 min-h-full">
    <div class="flex justify-center flex-col">
        <h1 class="text-4xl font-bold tracking-tight text-gray-900 sm:text-6xl">Admin Console</h1>
        <h2 class="text-xl font-bold tracking-tight text-gray-600 sm:text-1xl">Passwordless.dev</h2>
    </div>
    <div class="mt-8 sm:w-full sm:max-w-md">
        @if (TempData.ContainsKey("Message"))
        {
            <info-alert-box message="@TempData["Message"]"></info-alert-box>
        }
        <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10 flex flex-col space-y-4">
            <form class="space-y-4 flex flex-col" method="POST" v-on:submit.prevent="onSubmit">
                <div>
                    <label for="email" class="block text-sm font-medium leading-6 text-gray-900">Email address</label>
                    <div class="mt-2">
                        <input id="email" name="email" type="email" autocomplete="webauthn" class="block w-full p-2 rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary-500 sm:text-sm sm:leading-6">
                    </div>
                </div>
                @switch (Model.Status)
                {
                    case LoginModel.LoginStatus.EmailSent:
                    case LoginModel.LoginStatus.MagicLinkDisabled:
                        <success-alert-box message="We've sent you a magic link to automatically sign you in. (if we recognized the email)"></success-alert-box>
                        break;
                }
                <div class="feedback__unknown_credential hidden">
                    <Feedback name="_error" message="Sorry, we don't recognize that passkey. Do you have another one?" />
                </div>
                <button type="submit" class="btn-primary">Sign in</button>
                <div id="webauthn-unsupported-alert" class="hidden">
                    <danger-alert-box message="WebAuthn is not supported in this browser."></danger-alert-box>
                </div>
            </form>
            <hr class="h-px my-8 bg-gray-200 border-0">
            <form class="flex flex-col" method="post" asp-page-handler="SignUp">
                <button class="btn-secondary">Sign up</button>
            </form>
        </div>
    </div>
</div>

@section Scripts {
    <script type="module">
        import { createApp, ref } from 'vue';
        createApp({
            setup() {

                async function signIn(token) {
                    var res = await fetch("/passwordless-login", {
                        method: "POST",
                        body: JSON.stringify({ token }),
                        headers: {
                            RequestVerificationToken: "@requestToken",
                            "Content-Type": "application/json"
                        }
                    });

                    if (res.ok) {
                        location.href = "/Organization/Overview";
                    }

                    return res;
                }

                const p = new Passwordless.Client({
                    apiUrl: "@ManagementOptions.Value.ApiUrl",
                    apiKey: "@PasswordlessOptions.Value.ApiKey"
                });

                const showFeedback = (name) => {
                    const feedback = document.querySelector(`.${name}`);
                    if (feedback) {
                        feedback.classList.remove("hidden");
                    }
                }

                const autoFill = async () => {
                    const {token, error} = await p.signinWithAutofill();
                    if (error) {
                        if (error.errorCode === "unknown_credential") {
                            showFeedback("feedback__unknown_credential");
                        }
                    } else {
                        await signIn(token);
                    }

                };
                autoFill();

                const onSubmit = async (e) => {
                    let res = null;
                    const alias = new FormData(e.target).get("email");

                    try {
                        const {token, error} = await p.signinWithAlias(alias);
                        if (token)  {
                            res = await signIn(token);
                        }
                    } catch (e) {
                    }

                    const passkeysFailed = (!res || !res.ok);
                    if (passkeysFailed && alias) {
                        e.target.submit();
                    }
                };

                return {
                    onSubmit
                }
        }}).mount('#xapp');
	</script>
    <script type="module">
        const isSupported = Passwordless.isBrowserSupported();
        if (!isSupported) {
            const alert = document.getElementById("webauthn-unsupported-alert");
            alert.classList.remove("hidden");
        }
    </script>
}
